var express = require('express');
var router = express.Router();
var {DaddressModel} = require('../model/modelyzp');
/* GET home page. */

// 收货地址渲染
router.get('/daddress', async(req, res)=> {
  let data = await DaddressModel.find()
  res.send({
    data,
    code:200
  })
});

//收货地址添加
router.post('/address', async(req, res)=> {
    // console.log(req.body);
    await DaddressModel.create(req.body)
   
  });

// 智能获取地址
router.post('/zndz', async(req,res)=>{
    let body = req.body.body
    // console.log(body);
    let data = await main(body)
    console.log(data);
    res.send({
        data:data,
        code:200
    })
})  

const axios = require('axios');
const AK = "uBQSMe8xoBzvPRX8CZcZoBfq"
const SK = "iWdl1MW209vmbZduY499kLc96lNlJYKE"

async function main(body) {
    var options = {
        'method': 'POST',
        'url': 'https://aip.baidubce.com/rpc/2.0/nlp/v1/address?access_token=' + await getAccessToken(),
        'headers': {
                'Content-Type': 'application/json',
                'Accept': 'application/json'
        },
        data: JSON.stringify({
            "text": body
        })

    };

   const res = await axios(options)
   return res.data
        // .then(response => {
        //     console.log(response.data);
        //     return response.data
        // })
        // .catch(error => {
        //     throw new Error(error);
        // })
}

/**
 * 使用 AK，SK 生成鉴权签名（Access Token）
 * @return string 鉴权签名信息（Access Token）
 */
function getAccessToken() {

    let options = {
        'method': 'POST',
        'url': 'https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id=' + AK + '&client_secret=' + SK,
    }
    return new Promise((resolve, reject) => {
      axios(options)
          .then(res => {
              resolve(res.data.access_token)
          })
          .catch(error => {
              reject(error)
          })
    })
}







module.exports = router;